package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func deleteDuplicates(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	var pre, key, next *ListNode
	key = head
	next = key.Next

	var result *ListNode = &ListNode{}
	tail := result

	for {
		tail.Next = nil
		if pre == nil {
			if key.Val != next.Val {
				tail.Next = key
				tail = tail.Next
			}
			pre = key
			key = next
			next = next.Next
			continue
		}
		if next == nil {
			if key.Val != pre.Val {
				tail.Next = key
				tail = tail.Next
				tail.Next = nil
			}
			break
		}
		if pre.Val != key.Val && key.Val != next.Val {
			tail.Next = key
			tail = tail.Next
		}
		pre = key
		key = next
		next = next.Next
		continue

	}
	tail.Next = nil
	return result.Next
}

func main() {
	var head *ListNode = &ListNode{}
	t := head
	s := []int{1, 2, 3, 3, 4, 4, 5}
	for _, v := range s {
		t.Next = &ListNode{
			Val:  v,
			Next: nil,
		}
		t = t.Next
	}
	head = head.Next
	r := deleteDuplicates(head)
	for {
		if r == nil {
			break
		}
		fmt.Println(r.Val)
		r = r.Next
	}

}
